//
//  XMGKeyboardPackage.swift
//  CXSwiftWB
//
//  Created by meidaeriOS on 2017/6/7.
//  Copyright © 2017年 meidaer. All rights reserved.
//

import UIKit

class XMGKeyboardPackage: NSObject {
    /// 当前组的名称
    var group_name_cn: String?
    /// 当前组对应的文件夹名称
    var id: String?
    /// 当前组所有的表情
    var emoticons: [KeyboardEmoticon]?
    
    init(id: String) {
        self.id = id
    }
    
    /// 加载所有组数据
    class func loadEmotionPackages() -> [XMGKeyboardPackage] {
        
        var models: [XMGKeyboardPackage] = []
        // 0.手动添加最近组
        let package = XMGKeyboardPackage(id: "")
        package.appendEmptyEmoticons()
        models.append(package)
        
        // 1.加载emoticons.plist文件
        // 1.1获取emoticons.plist文件路径
        let path = Bundle.main.path(forResource: "emoticons.plist", ofType: nil, inDirectory: "Emoticons.bundle")!
        // 1.2加载emoticons.plist
        let dict = NSDictionary(contentsOfFile: path)!
        let array = dict["packages"] as! [[String: AnyObject]]
        // 2.取出所有组表情
        
        for packageDict in array
        {
            // 2.1创建当前组模型
            let package = XMGKeyboardPackage(id: packageDict["id"] as! String)
            // 2.2加载当前组所有的表情数据
            package.loadEmoticons()
            // 2.3补全一组数据, 保证当前组能被21整除
            package.appendEmptyEmoticons()
            // 2.4将当前组模型添加到数组中
            models.append(package)
        }
        return models
    }
    
    /// 加载当前组所有表情
    fileprivate func loadEmoticons()
    {
        // 1.拼接当前组info.plist路径
        let path = Bundle.main.path(forResource: self.id, ofType: nil, inDirectory: "Emoticons.bundle")!
        let filePath = (path as NSString).appendingPathComponent("info.plist")
        // 2.根据路径加载info.plist文件
        let dict = NSDictionary(contentsOfFile: filePath)!
        // 3.从加载进来的字典中取出当前组数据
        // 3.1取出当前组名称
        group_name_cn = dict["group_name_cn"] as? String
        // 3.2取出当前组所有表情
        let array = dict["emoticons"] as! [[String: AnyObject]]
        // 3.3遍历数组, 取出每一个表情
        var models = [KeyboardEmoticon]()
        
        var index = 0
        for emoticonDict in array
        {
            if index == 20
            {
                let emoticon = KeyboardEmoticon(isRemoveButton: true)
                models.append(emoticon)
                index = 0
                continue
            }
            
            let emoticon = KeyboardEmoticon(dict: emoticonDict, id: self.id!)
            models.append(emoticon)
            index += 1
        }
        emoticons = models
    }
    
    /// 补全一组数据, 保证当前组能被21整除
    fileprivate func appendEmptyEmoticons()
    {
        // 0.判断是否是最近组
        if emoticons == nil
        {
            emoticons = [KeyboardEmoticon]()
        }
        
        // 1.取出不能被21整除剩余的个数
        let number = emoticons!.count % 21
        // 2.补全
        for _ in number..<20 {
            let emoticon = KeyboardEmoticon(isRemoveButton: false)
            emoticons?.append(emoticon)
        }
        
        // 3.补全删除按钮
        let emoticon = KeyboardEmoticon(isRemoveButton: true)
        emoticons?.append(emoticon)
    }
    
    func addFavoriteEmotin(_ emotion: KeyboardEmoticon) {
        emoticons?.removeLast()
        
        // 判断是否添加过
        if !emoticons!.contains(emotion) {
            emoticons?.removeLast()
            emoticons?.append(emotion)
        }
        
        let array = emoticons?.sorted(by: { (e1, e2) -> Bool in
            return e1.count > e2.count
        })
        
        emoticons = array
        
        emoticons?.append(KeyboardEmoticon(isRemoveButton: true))
    }
}

/// 替换字符传中的表情
extension XMGKeyboardPackage {
    
    class func createMutableAttrString(_ str: String, font: UIFont) -> NSMutableAttributedString {
        let pattern = "\\[.*?\\]"
        
        let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
        let results = regex.matches(in: str, options: .init(rawValue: 0), range: NSMakeRange(0, str.characters.count))
        
        let attrMStr = NSMutableAttributedString(string: str)
        
        for i in (0 ..< results.count).reversed() {
            let result = results[i]
            let chs = (str as NSString).substring(with: result.range)
            
            let pngPath = findPngPath(chs)
            
            guard pngPath != nil else {
                continue
            }
            
            let attachment = NSTextAttachment()
            attachment.image = UIImage(contentsOfFile: pngPath!)
            attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight)
            let emoAttrStr = NSAttributedString(attachment: attachment)
            
            // 4.4 替换表情
            attrMStr.replaceCharacters(in: result.range, with: emoAttrStr)
        }
        return attrMStr
    }
    
    class func findPngPath(_ chs : String) -> String? {
        // 1.加载所有的表情
        let packages = XMGKeyboardPackage.loadEmotionPackages()
        
        // 2.遍历所有的表情包,拿到chs对应的pngPath
        for package in packages {
            // 2.1.如果表情包没有值,则该表情包不需要再进行遍历
            guard let emoticons = package.emoticons else {
                print("该表情包没有值")
                continue
            }
            
            // 2.2.定义表情pngPath
            var pngPath : String?
            
            // 2.3.遍历每一个表情包中的表情
            for emoticon in emoticons {
                // 2.3.1.如果该表情的chs属性为空,则遍历下一个表情
                guard let emoticonChs = emoticon.chs else {
                    continue
                }
                
                // 2.3.2.如果chs不为空,则判断表情的chs是否和传入的chs相等
                // 如果相同:则将pngPath取出
                if emoticonChs == chs {
                    pngPath = emoticon.pngPath
                    break
                }
            }
            
            // 2.4.如果遍历了一个表情包种已经取出了pngPath,则不需要再遍历下一个表情包
            if pngPath != nil {
                return pngPath
            }
        }
        
        // 3.如果遍历了所以的表情包依然没有值,则直接返回nil
        return nil
    }

}
